<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\model;


use think\Model;
use think\Response;

class Log extends BaseModel
{
    public static function write(Response $response, $platform = "mall")
    {

        global $user;
        $method = request()->method();
        if ($method == "GET") {
            return false;
        }

        $data = [
            'url' => request()->url(true),
            'admin_id' => $user->id ?? 0,
            'admin_name' => $user['name'] ?? '',
            'mall_id' => $user->mall_id ?? 0,
            'request_param' => json_encode(input(), JSON_UNESCAPED_UNICODE),
            'create_time' => date("Y-m-d H:i:s", time()),
            'platform' => $platform,
            'ip' => getIp(),
            'method' => $method,
        ];
        try {
            $ruleDesc = self::getRuleDesc();

            if (is_array($ruleDesc)) {
                $data = array_merge($data, $ruleDesc, self::getResponseData($response));
                $model = new self();
                $model->save($data);
                return $model;
            }
        } catch (\Throwable $e) {
            //todo 待写
            #dd($e->getMessage());
        }
    }

    public static function getResponseData($response)
    {

//            $data = $response->getData();
        if ($response){
            $code = $response->getCode();
        }
        return [
            'code' => $code ?? 0,
            'message' => json_encode([]),#is_array($data['msg']) ? json_encode($data['msg'], JSON_UNESCAPED_UNICODE) : $data['msg'] ?? '',
            'data' => json_encode([]), #is_array($data) ? json_encode($data['msg'], JSON_UNESCAPED_UNICODE) : $data ?? '',
        ];


    }

    public static function getRuleDesc()
    {
        $pageAction = request()->header('PageAction');

        if (empty($pageAction)) {
            return false;
        }
        $explode = explode(",", $pageAction);
        if (count($explode) < 2) {
            return false;
        }
        $level = (int)$explode[0];
        $action = (string)$explode[1];
        $rule = \app\madmin\model\Rule::where(['resource' => $action, 'level' => $level])->find()->toArray();

        if (empty($rule)) {
            return false;
        }
        if ($rule['resource'] == "read") {
            return false;
        }

        return [
            'title' => $rule['resource_name'] . '>>>' . $rule['group'],
            'action' => $rule['name'],
        ];
    }
}